﻿using UnityEngine;
using System.Collections;

public class Squad : Unit {

	Vector3 _targetPosition;
	Vector3 _moveVector;
	float _hitTimer = 0f; 
	float _speed = 0f;
	float _friction = 0.95f;
	
	Quaternion _angle = Quaternion.identity;
	
	void Awake()
	{
		_name = "Squad";
		_defense = 0.75f;
		_attack = 25f;
		_attackSpeed = 1.5f;
		_maxSpeed = 1f;
		_acceleration = 0.5f;
		_turnSpeed = 180f;
		
		CreateStateMachine();

		if (null != _hexagon) 
		{
			_hexagon.Unit = this;
		}
	}

	private void CreateStateMachine()
	{
		_stateMachine.CreateState( "Stand", _StateIdleInit, _StateIdleUpdate, null );
		_stateMachine.CreateState( "Turn", _StateTurnInit, _StateTurnUpdate, null );
		_stateMachine.CreateState( "Move", _StateAdvanceInit, _StateAdvanceUpdate, null );
	}
	
	private void _StateIdleInit()
	{
		_hitTimer = _attackSpeed;
	}
	
	private void _StateIdleUpdate()
	{	
		_hitTimer -= Time.deltaTime;
		if( _hitTimer < 0f )
		{
			_hitTimer += _attackSpeed;
			_eventHandler.DispatchEvent<float, HCHexagonController.EType>("OnHit", _attack, _faction );
		}
	}
	
	private void _StateTurnInit()
	{
		
		// get angle to target
		Vector3 _relative = _targetPosition - transform.position;
		Quaternion _to = Quaternion.LookRotation( _relative );
		float _quatAngle = Quaternion.Angle( transform.rotation, _to );
		
		if( _quatAngle == 0 )
		{
			_stateMachine.ChangeState("Move");
		}else{
			TweenRotation _rot = TweenRotation.Begin( gameObject, _quatAngle / _turnSpeed, _to );
			_rot.onFinished = delegate(UITweener tween) {
				_stateMachine.ChangeState("Move");
			};
		}
	}
	
	private void _StateTurnUpdate()
	{	
	
	}
	
	private void _StateAdvanceInit()
	{
		TweenPosition _pos = TweenPosition.Begin( gameObject, _maxSpeed, _targetPosition );
		_pos.onFinished = delegate(UITweener tween) {
			_stateMachine.ChangeState("Stand");
		};
		_pos.animationCurve = _moveCurve;
	}
	
	private void _StateAdvanceUpdate()
	{	
			
	}
	
	// Use this for initialization
	void Start () 
	{
	
	}
	
	// Update is called once per frame
	void Update () 
	{
		_stateMachine.Update();
	}
	
	void LateUpdate()
	{
		_stateMachine.LateUpdate();
	}
	
	override
	public bool canMove
	{
		get{ return _stateMachine.currentState.code == (int)EStates.STAND ; }
	}
	
	override
	public void MoveTo(Vector3 _position)
	{
		//Debug.Log("Squad Moving from " + transform.position.ToString() + " to " + _position.ToString() );
		// find angle to destiny
		
		
		if( !canMove ) return;
		
		_targetPosition = new Vector3( _position.x, transform.position.y, _position.z );
		_stateMachine.ChangeState( "Turn" );
	}
}
